package com.mbl.base.modular.base.controller;


import cn.hutool.core.io.FileUtil;
import com.mbl.base.core.common.controller.BaseController;
import com.mbl.base.core.common.dto.MblResult;
import com.mbl.base.core.modular.storage.StorageService;
import com.mbl.base.modular.base.entity.Storage;
import com.mbl.base.modular.base.service.IStorageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * <p>
 * 文件存储表 前端控制器
 * </p>
 *
 * @author lwj
 * @since 2020-02-27
 */
@RestController
@RequestMapping("/base/storage")
public class StorageController extends BaseController<Storage, IStorageService> {

    @Autowired
    private StorageService storageService;
    @Autowired
    private IStorageService iStorageService;
    @PostMapping("/create")
    public Object create(@RequestParam("file") MultipartFile file) {
        Storage store = null;
        String originalFilename = file.getOriginalFilename();
        try {
            store = storageService.store(file.getInputStream(), file.getSize(),
                    file.getContentType(), originalFilename);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return MblResult.success(store);
    }

    /**
     * 访问存储对象
     *
     * @param key 存储对象key
     * @return
     */
    @GetMapping("/fetch/excel/{key:.+}")
    public ResponseEntity<byte[]> fetchExcel(@PathVariable String key) {
        final byte[] bytes = FileUtil.readBytes("/excel/" + key);
        return ResponseEntity.ok().body(bytes);
    }

    /**
     * 访问存储对象
     *
     * @param key 存储对象key
     * @return
     */
    @GetMapping("/fetch/{key:.+}")
    public ResponseEntity<Resource> fetch(@PathVariable String key) {
        final Resource file = getFile(key);
        if (file == null) {
            return ResponseEntity.notFound().build();
        }
        return ResponseEntity.ok().contentType(getType(key)).body(file);
    }

    /**
     * 访问存储对象
     *
     * @param key 存储对象key
     * @return
     */
    @GetMapping("/download/{key:.+}")
    public ResponseEntity<Resource> download(@PathVariable String key) {
        final Resource file = getFile(key);
        if (file == null) {
            return ResponseEntity.notFound().build();
        }
        return ResponseEntity.ok().contentType(getType(key)).header(HttpHeaders.CONTENT_DISPOSITION,
                "attachment; filename=\"" + file.getFilename() + "\"").body(file);
    }

    private Resource getFile(String key){
        if (key == null || key.contains("../")) {
            return null;
        }
        Resource file = storageService.loadAsResource(key);
        if (file == null) {
            return null;
        }
        return file;
    }

    private MediaType getType(String key) {
        Storage storage = iStorageService.getByKey(key);
        String type = storage.getType();
        MediaType mediaType = MediaType.parseMediaType(type);
        return mediaType;
    }
}

